import React, { useState } from 'react'
import {useSelector, useDispatch} from 'react-redux'
import { decrementAction, incrementAction, incrementAsyncAction } from '../../redux/counter'

export default function CounterUpdate() {
  const [num, setNum] = useState(1)
  const count = useSelector(state => state.count)
  const dispatch = useDispatch()

  // 增加
  const increment = () => {
    dispatch(incrementAction(num))
  }
  // 减少
  const decrement = () => {
    dispatch(decrementAction(num))
  }
  // 奇数增加
  const incrementIfOdd = () => {
    if (count%2===1) {
      dispatch(incrementAction(num))
    }
  }
  // 延迟增加
  const incrementAsync = () => {
    dispatch(incrementAsyncAction(num))
  }

  return (
    <div>
      <select value={num} onChange={e => setNum(e.target.value * 1)}>  {/* *1保证num是数值 */}
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button onClick={increment}>增加</button>
      <button onClick={decrement}>减少</button>
      <button onClick={incrementIfOdd}>奇数增加</button>
      <button onClick={incrementAsync}>延迟1S增加</button>
    </div>
  )
}
